package com.shenke.permission.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenke.permission.constant.RoleConstant;
import com.shenke.permission.model.Role;
import com.shenke.permission.model.UserRole;
import com.shenke.permission.service.RoleService;
import com.shenke.permission.service.UserRoleService;
import com.shenke.permission.mapper.UserRoleMapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author 86180
* @description 针对表【user_roles】的数据库操作Service实现
* @createDate 2025-06-16 20:22:12
*/
@Service
@Slf4j
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole>
    implements UserRoleService {

    @Resource
    private RoleService roleService;

    /**
     * 绑定默认角色（普通用户）
     * @param userId
     */
    @Override
    public boolean bindDefaultRole(Long userId) {
        log.info("开始为用户[userId={}]绑定默认角色", userId);
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        UserRole userRole = this.getOne(queryWrapper.eq(UserRole::getUserId, userId));
        if (userRole != null) {
            log.error("用户[userId={}]已绑定角色[roleId={}]，无法绑定默认角色", userId, userRole.getRoleId());
            return false;
        }
        userRole = new UserRole();
        userRole.setUserId(userId);
        userRole.setRoleId(RoleConstant.USER);
        boolean save = this.save(userRole);
        if (!save) {
            log.error("绑定默认角色失败，用户[userId={}]", userId);
        } else {
            log.info("成功为用户[userId={}]绑定默认角色[roleId={}]", userId, RoleConstant.USER);
        }
        return save;
    }

    /**
     * 根据 id 查询用户角色码
     * @param userId
     * @return role_code
     */
    @Override
    public String getUserRoleCode(Long userId) {
        log.info("查询用户[userId={}]的角色码", userId);
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        UserRole userRole = this.getOne(queryWrapper.eq(UserRole::getUserId, userId));
        if (userRole == null) {
            log.error("查询角色码失败：用户[userId={}]不存在", userId);
            return RoleConstant.UNDEFINED_CODE;
        }
        Role role = roleService.getById(userRole.getRoleId());
        if (role == null || StringUtils.isBlank(role.getRoleCode())) {
            log.error("查询角色码失败：用户[userId={}]对应的角色[roleId={}]不存在或角色码为空", 
                      userId, userRole.getRoleId());
            return RoleConstant.UNDEFINED_CODE;
        }
        log.info("成功获取用户[userId={}]的角色码[roleCode={}]", userId, role.getRoleCode());
        return role.getRoleCode();
    }

    /**
     * 升级用户为管理员
     * @param userId
     */
    @Override
    public void upgradeToAdmin(Long userId) {
        log.info("开始将用户[userId={}]升级为管理员", userId);
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        UserRole userRole = this.getOne(queryWrapper.eq(UserRole::getUserId, userId));
        if (userRole == null) {
            log.error("升级失败：用户[userId={}]不存在", userId);
            return;
        }
        if (userRole.getRoleId() == RoleConstant.SUPER_ADMIN) {
            log.error("升级失败：用户[userId={}]为超级管理员[roleId={}]，不能升级为管理员", 
                     userId, RoleConstant.SUPER_ADMIN);
            return;
        }
        if (userRole.getRoleId() == RoleConstant.ADMIN) {
            log.error("升级失败：用户[userId={}]已经是管理员[roleId={}]", userId, RoleConstant.ADMIN);
            return;
        }
        Integer oldRoleId = userRole.getRoleId().intValue();
        userRole.setRoleId(RoleConstant.ADMIN);
        boolean save = this.updateById(userRole);
        if (!save) {
            log.error("更新数据库失败：用户[userId={}]升级为管理员操作未能保存", userId);
        } else {
            log.info("成功将用户[userId={}]从角色[roleId={}]升级为管理员[roleId={}]", 
                    userId, oldRoleId, RoleConstant.ADMIN);
        }
    }

    /**
     * 降级用户为普通角色
     * @param userId
     */
    @Override
    public void downgradeToUser(Long userId) {
        log.info("开始将用户[userId={}]降级为普通用户", userId);
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        UserRole userRole = this.getOne(queryWrapper.eq(UserRole::getUserId, userId));
        if (userRole == null) {
            log.error("降级失败：用户[userId={}]不存在", userId);
            return;
        }
        if (userRole.getRoleId() == RoleConstant.SUPER_ADMIN) {
            log.error("降级失败：用户[userId={}]为超级管理员[roleId={}]，不能降级为普通用户", 
                     userId, RoleConstant.SUPER_ADMIN);
            return;
        }
        if (userRole.getRoleId() == RoleConstant.USER) {
            log.error("降级失败：用户[userId={}]已经是普通用户[roleId={}]", userId, RoleConstant.USER);
            return;
        }
        Integer oldRoleId = userRole.getRoleId().intValue();
        userRole.setRoleId(RoleConstant.USER);
        boolean save = this.updateById(userRole);
        if (!save) {
            log.error("更新数据库失败：用户[userId={}]降级为普通用户操作未能保存", userId);
        } else {
            log.info("成功将用户[userId={}]从角色[roleId={}]降级为普通用户[roleId={}]", 
                    userId, oldRoleId, RoleConstant.USER);
        }
    }

    /**
     * 根据角色码查询用户 id 列表
     * @param roleCode
     * @return
     */
    @Override
    public List<Long> listUserByRoleCode(String roleCode) {
        log.info("开始根据角色码[roleCode={}]查询用户列表", roleCode);
        if (roleCode == null) {
            log.error("查询失败：roleCode为空");
            return null;
        }
        LambdaQueryWrapper<Role> roleQueryWrapper = new LambdaQueryWrapper<>();
        Role role = roleService.getOne(roleQueryWrapper.eq(Role::getRoleCode, roleCode));
        if (role == null) {
            log.error("查询失败：角色码[roleCode={}]对应的角色不存在", roleCode);
            return null;
        }
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        List<UserRole> userRoleList = this.list(queryWrapper.eq(UserRole::getRoleId, role.getRoleId()));
        List<Long> userIdList = userRoleList.stream()
                .map(UserRole::getUserId)
                .collect(Collectors.toList());
        log.info("成功查询到角色码[roleCode={}, roleId={}]对应的用户列表，共{}个用户", 
                roleCode, role.getRoleId(), userIdList.size());
        return userIdList;
    }
}




